﻿using System.Web;
using Orchard;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.Descriptors;
using Orchard.Environment;
using Orchard.UI.Navigation;

// ReSharper disable InconsistentNaming

namespace ContentCreator.Services {
    public class ContentCreatorShapes : IShapeTableProvider {
        private readonly Work<INavigationManager> _navigationManager;
        private readonly Work<WorkContext> _workContext;
        private readonly Work<IShapeFactory> _shapeFactory;

        public ContentCreatorShapes(
            Work<INavigationManager> navigationManager,
            Work<WorkContext> workContext,
            Work<IShapeFactory> shapeFactory) {
            _navigationManager = navigationManager;
            _workContext = workContext;
            _shapeFactory = shapeFactory;
        }

        public void Discover(ShapeTableBuilder builder) {
            builder.Describe("ContentCreator")
                   .OnDisplaying(displaying => {
                       ContentItem contentItem = displaying.Shape.ContentItem;
                       if (contentItem != null) {
                           displaying.ShapeMetadata.Alternates.Add("ContentCreator_" + displaying.ShapeMetadata.DisplayType);
                       }
                   });
        }

        [Shape]
        public IHtmlString ContentCreatorNavigation(dynamic Display) {
            var menuItems = _navigationManager.Value.BuildMenu("content-creator");

            // Set the currently selected path
            var selectedPath = NavigationHelper.SetSelectedPath(menuItems, _workContext.Value.HttpContext.Request.RequestContext.RouteData);

            dynamic shapeFactory = _shapeFactory.Value;

            // Populate local nav
            dynamic localMenuShape = shapeFactory.LocalMenu().MenuName("content-creator");
            NavigationHelper.PopulateLocalMenu(shapeFactory, localMenuShape, localMenuShape, selectedPath);
            return Display(localMenuShape);
        }
    }
}